package cn.com.huzo.service.tech.impl;

import cn.com.huzo.model.entities.tech.MrpHeaderEntity;
import cn.com.huzo.model.entities.tech.MrpLinesAssortmentEntity;
import cn.com.huzo.repository.tech.MrpHeaderRepository;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.tech.MrpLinesAssortmentRepository;
import cn.com.huzo.service.tech.MrpLinesAssortmentManager;
import cn.com.huzo.repository.tech.MrpLinesResultRepository;
import org.apache.commons.collections4.MapUtils;

/**
 * 物料需求计划-材料搭配明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("MrpLinesAssortmentManager")
public class MrpLinesAssortmentManagerImpl extends GenericManagerImpl<MrpLinesAssortmentEntity, String>
        implements MrpLinesAssortmentManager {

    @Resource(name = "MrpHeaderRepository")
    private MrpHeaderRepository _dao;

    @Resource(name = "MrpLinesAssortmentRepository")
    private MrpLinesAssortmentRepository _dao_lines_assort;

    @Resource(name = "MrpLinesResultRepository")
    private MrpLinesResultRepository _dao_lines_result;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public List<MrpLinesAssortmentEntity> fetchAssortmentByHeaderId(Long headerId) throws Exception {
        return _dao_lines_assort.fetchByHeaderId(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        Integer rowsAffected = _dao_lines_assort.delete(MapUtils.getString(criterion, "LinesId"));
        if (rowsAffected > 0) {
            // 更新主表操作时间，为了排序
            _dao.updateLastTime(MapUtils.getLong(criterion, "HeaderId"));
            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "技术管理→物料需求计划明细（搭配计算）",
                    "明细数据（" + MapUtils.getString(criterion, "LinesData") + "）",
                    "删除");
        }

        _result.put("AssortmentLinesList", _dao_lines_assort.fetchByHeaderId(MapUtils.getLong(criterion, "HeaderId")));
        _result.put("MrpLinesList", _dao_lines_result.fetchByHeaderId(MapUtils.getLong(criterion, "HeaderId")));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchDelete(List<MrpLinesAssortmentEntity> itemList) throws Exception {
        Integer rowsAffected = _dao_lines_assort.batchDelete(itemList);
        if (rowsAffected > 0) {
            // 更新主表操作时间，为了排序
            _dao.updateLastTime(itemList.get(0).getHeaderId());
            for (int i = 0; i < itemList.size(); i++) {
                MrpLinesAssortmentEntity instance = itemList.get(i);
                // 审计日志
                //writeAuditLog(instance.getDeletedBy(), "技术管理→物料需求计划明细（搭配计算）",
                //        "[料号]：" + instance.getMaterialCode() + "　[使用部位]：" + instance.getPartOfNeed(), "删除");
            }
        }

        Map<String, Object> _result = new HashMap();
        _result.put("AssortmentLinesList", _dao_lines_assort.fetchByHeaderId(itemList.get(0).getHeaderId()));
        _result.put("MrpLinesList", _dao_lines_result.fetchByHeaderId(itemList.get(0).getHeaderId()));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchAssort(List<MrpLinesAssortmentEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();

        if (itemList != null && itemList.size() > 0) {
            Long headerId = itemList.get(0).getHeaderId();

            for (int i = 0; i < itemList.size(); i++) {
                MrpLinesAssortmentEntity instance = itemList.get(i);

                // 首先更新搭配类型
                _dao_lines_assort.update(instance);
                // 删除原有的该材料的物料搭配需求
                _dao_lines_result.deleteByAssortmentLinesId(instance.getLinesId());
                // 重新计算物料需求
                _dao_lines_assort.singleAssort(instance.getHeaderId(),
                        instance.getLinesId(),
                        instance.getMoHeaderId(),
                        instance.getStyleNo(),
                        instance.getAssortmentSize(),
                        instance.getAssortmentType(),
                        instance.getCalByDestinationFlag(),
                        instance.getAssortmentDestination());
                // 删除搭配计算用尺码
                _dao_lines_assort.deleteLinesAssortmentSize(instance.getHeaderId(), instance.getLinesId());
                // 重新记录计算用尺码
                if (instance.getAssortmentSize() != null && !instance.getAssortmentSize().isEmpty()) {
                    _dao_lines_assort.insertLinesAssortmentSize(instance.getHeaderId(),
                            instance.getLinesId(),
                            instance.getAssortmentSize());
                }

                // 审计日志
                //writeAuditLog(instance.getUpdatedBy(), "技术管理→物料需求计划明细（搭配计算）",
                //        "[料号]：" + instance.getMaterialCode() + "　[使用部位]：" + instance.getPartOfNeed(),
                //        "搭配计算");
            }

            // 如果是定版调达表
            if (itemList.get(0).getBillType() == 1) {
                // 取得提前组料单
                MrpHeaderEntity _prior_instance = _dao.fetchPriorMrpByStyleNo(itemList.get(0).getStyleNo(), itemList.get(0).getMoHeaderId());
                if (_prior_instance != null) {
                    // 通过提前组料单更新定版调达的提前组料数、规格、备注，并重新计算补给数
                    _dao_lines_result.updateByPriorMrpLines(headerId, _prior_instance.getHeaderId(), itemList.get(0).getUpdatedBy());
                }
            }
            _result.put("Success", true);
            _result.put("AssortmentLinesList", _dao_lines_assort.fetchByHeaderId(headerId));
            _result.put("MrpLinesList", _dao_lines_result.fetchByHeaderId(headerId));
            //return _dao_lines_result.fetchByHeaderId(headerId);
        } else {
            _result.put("Success", false);
            //List<MrpLinesResultEntity> _rtn = new ArrayList();
            //return _rtn;
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesForSyncBom(Long headerId, Long bomHeaderId, Long moHeaderId, String styleNo, Long updatedBy) throws Exception {
        Integer rowsAffected = _dao_lines_assort.deleteLinesForSyncBom(headerId, bomHeaderId);
        rowsAffected += _dao_lines_assort.insertLinesForSyncBom(headerId, bomHeaderId, updatedBy);

        // 刚刚插入的数据搭配类型为9，针对9做搭配计算（初始化为无搭配）
        _dao_lines_assort.batchAssort(headerId, moHeaderId, styleNo, (short) 9);
        // 更新类型 从 9 -> 0
        _dao_lines_assort.updateTypeForNewLines(headerId, updatedBy);

        // 更新主表操作时间，为了排序
        _dao.updateLastTime(headerId);

        // 审计日志
        //if (rowsAffected > 0) {
        //    writeAuditLog(updatedBy, "技术管理→物料需求计划明细（搭配计算）", "[款号]：" + styleNo, "同步单耗表");
        //}
        Map<String, Object> _result = new HashMap();
        _result.put("AssortmentLinesList", _dao_lines_assort.fetchByHeaderId(headerId));
        _result.put("MrpLinesList", _dao_lines_result.fetchByHeaderId(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer updateByHistoryData(Map<String, Object> criterion) throws Exception {
        Integer rowsAffected;

        // 第1步，删除物料需求明细
        _dao_lines_result.deleteByHeaderId(MapUtils.getLong(criterion, "HeaderId"));

        // 第2步，根据历史数据重新设定材料搭配类型
        rowsAffected = _dao_lines_assort.updateByHistoryData(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "OtherHeaderId"),
                MapUtils.getLong(criterion, "UpdatedBy"));

        // 第3步，根据设定好的搭配类型重新计算物料需求数据
        _dao_lines_assort.batchAssort(MapUtils.getLong(criterion, "HeaderId"),
                Long.parseLong(criterion.get("OtherHeaderKey").toString()),
                criterion.get("StyleNo").toString(),
                MapUtils.getShort(criterion, "AssortmentType"));

        // 第4步，根据历史数据做物料需求数据更新，主要是材料颜色、规格等信息
        rowsAffected += _dao_lines_result.updateByHistoryData(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "OtherHeaderId"),
                MapUtils.getLong(criterion, "UpdatedBy"));

        return rowsAffected;
    }
}
